<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>数组中负数索引或越界</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <div></div>
</body>
<script>
  "use strict"; {
    const arrProxy = arr => {
      if (!Array.isArray(arr)) throw TypeError("不是数组")
      return new Proxy(arr, {
        get(e, k) {
          // 表示数组的下标(字符串类型，需要强制装换一下)
          k = Number(k)
          // 数组的长度
          let len = e.length
          // 如果下标为负数，则从数组后面开始获取
          if (k < 0) {
            k = len + k
          }
          console.log("k ==", k)
          // 数组越界时，也能获取到对应的下标
          if (k >= len) {
            k = k % len
          }

          return e[k]
        },
        set(e, k, v) {
          // if()
        }
      })
    }

    let res = arrProxy([100, 20, "好的"])
    console.log(res[-4])
  };
</script>

</html>